package com.rabbitMQ.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer_Routing {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.23.129"); // 设置连接 ip 默认 localhost
        factory.setPort(5672);  // 设置连接端口 默认 5672
        factory.setVirtualHost("/root"); // 虚拟机 我们这里使用 /root
        factory.setUsername("root");    // 拥有权限的用户
        factory.setPassword("root");    // 拥有权限的用户密码
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 创建交换机
        /*
       exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
       参数：
        1. exchange:交换机名称
        2. type:交换机类型
            DIRECT("direct"),：定向
            FANOUT("fanout"),：扇形（广播），发送消息到每一个与之绑定队列。
            TOPIC("topic"),通配符的方式
            HEADERS("headers");参数匹配

        3. durable:是否持久化
        4. autoDelete:自动删除
        5. internal：内部使用。 一般false
        6. arguments：参数
        */
        String exchangeName = "Producer_Direct"; // 交换机名称
        String queue1Name = "Producer_Direct_Queues_1"; // 队列名称
        String queue2Name = "Producer_Direct_Queues_2"; // 队列名称
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, null);
        // 创建队列
        channel.queueDeclare(queue1Name, true, false, false, null);
        channel.queueDeclare(queue2Name, true, false, false, null);
        // 交换机和队列的绑定 加上路由
        channel.queueBind(queue1Name, exchangeName, "error");

        channel.queueBind(queue2Name, exchangeName, "error");
        channel.queueBind(queue2Name, exchangeName, "info");
        channel.queueBind(queue2Name, exchangeName, "warning");
        // 发送消息 error 消息
        channel.basicPublish(exchangeName, "error", null, ("Message Success Mode BuiltinExchangeType.DIRECT Result error").getBytes());
        // 发送 info 消息
        channel.basicPublish(exchangeName, "info", null, ("Message Success Mode BuiltinExchangeType.DIRECT Result info").getBytes());
        // 发送 success 消息
        channel.basicPublish(exchangeName, "success", null, ("Message Success Mode BuiltinExchangeType.DIRECT success").getBytes());
        // 关闭资源
        channel.close();
        connection.close();
    }
}